package amq.demo.local.consumer;

import studio.raptor.databus.client.DatabusConfig;
import studio.raptor.databus.client.DatabusConsumer;
import studio.raptor.databus.client.DatabusConsumerBuilder;
import studio.raptor.databus.command.Event;

import javax.jms.JMSException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.LockSupport;

/**
 * Created by koalton on 2017/7/15.<br>
 *
 * 模拟客户中心消费事件--ModifyOrder:100002
 */
public class CustomerCenter {
    static SimpleDateFormat SDF2S = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 消费者最大休眠时间，单位:秒
     */
    static int MAX_SLEEP_TIME = 15 ;
    /**
     * 消费者休眠时间增加步长时间，单位:秒
     */
    static int SLEEP_TIME_STEP = 2;
    /**
     * 消费者初始休眠时间，单位:秒
     */
    static int SLEEP_TIME_INIT = 1 ;
    /**
     * 消费者休眠时间
     */
    static int SLEEP_TIME = SLEEP_TIME_INIT ;
    public static void main(String[] args){
        try {
            DatabusConfig databusConfig = new DatabusConfig("Customer");
            DatabusConsumerBuilder consumerBuilder = new DatabusConsumerBuilder(databusConfig);
            DatabusConsumer consumer = consumerBuilder.create("ModifyOrder",100002);

            while (true){
                if ( SLEEP_TIME >= MAX_SLEEP_TIME ){
                    System.out.println("Customer consumer stop and exit .");
                    break;
                }
                Event event = consumer.receive(1*1000);
                if (event != null) {
                    SLEEP_TIME = SLEEP_TIME_INIT;
                    System.out.println(event);
                }else{
                    System.out.println("At "+SDF2S.format(new Date())+" receive no message.");
                    LockSupport.parkUntil(System.currentTimeMillis()+SLEEP_TIME*1000);
                    SLEEP_TIME += SLEEP_TIME_STEP ;
                }
            }

        } catch (JMSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
